package com.sakura.thread.chapter10;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by apple on 2018/12/21.
 */
public class CyclicBarrierTest2 {
    //创建一个CyclicBarrier实例
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(new Runnable() {
            @Override
            public void run() {

                try {
                    System.out.println(Thread.currentThread() + "step1");
                    cyclicBarrier.await();

                    System.out.println(Thread.currentThread() + "step2");
                    cyclicBarrier.await();

                    System.out.println(Thread.currentThread() + "step3");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }


            }
        });

        executorService.submit(new Runnable() {
            @Override
            public void run() {

                try {
                    System.out.println(Thread.currentThread() + "step1");
                    cyclicBarrier.await();

                    System.out.println(Thread.currentThread() + "step2");
                    cyclicBarrier.await();

                    System.out.println(Thread.currentThread() + "step3");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }


            }
        });

        executorService.shutdown();

    }
}
